package com.xds.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xds.gulimall.product.service.CategoryBrandRelationService;
import com.xds.gulimall.product.vo.html.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xds.common.utils.PageUtils;
import com.xds.common.utils.Query;

import com.xds.gulimall.product.dao.CategoryDao;
import com.xds.gulimall.product.entity.CategoryEntity;
import com.xds.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
     //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装父子结构
          //2.1 找到所有一集分类
        List<CategoryEntity> level1Menu = entities.stream().filter(categoryEntity->
            categoryEntity.getParentCid() == 0
        ).map((menu->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        })).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return  level1Menu;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的对方引用
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 返回完整路径
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return  parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     *  @CacheEvict 失效模式
     *   @Caching 进行多种缓存操作
     */
    @Override
    @Transactional

//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category",key = "'getCatelogJson'")
//    })
    @CacheEvict(value = "category",allEntries = true)
    public void updateCasxdae(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("方法调用getLevel1Categorys");
        List<CategoryEntity> OneCategory = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return OneCategory;
    }

    @Override
    @Cacheable(value = "category",key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    //每一个的一级分类，查到这个一级分类下的二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {

                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //找当前分类的三级分类
                            List<CategoryEntity> level3Vo = getParent_cid(selectList,l2.getCatId());
                            if (level3Vo!=null){
                                List<Catelog2Vo.Catelog3Vo> collect = level3Vo.stream().map(l3 -> {
                                    //封装指定格式
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());


                    }

                    return catelog2Vos;
                }

        ));


        return parent_cid;
    }

    /**
     * 查出所有的分离
     * @return
     */
    public  Map<String, List<Catelog2Vo>> getCatelogJson2() {
        //1。加入缓存逻辑
        String catalogjson = redisTemplate.opsForValue().get("catalogjson");
        if (StringUtils.isEmpty(catalogjson)){
            //2 没有从数据库调用
//            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithLocal();
            Map<String, List<Catelog2Vo>> catelogJsonFromDb = getCatelogJsonFromDbWithRedis();
            //3.将查到的数据放入redis缓存中
            return catelogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> result=JSON.parseObject(catalogjson,new TypeReference< Map<String, List<Catelog2Vo>>>(){});
        return result;
    }
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisson() {

            //1.获取分布锁锁
         RLock lock = redisson.getLock("catelogJson-lock");
         lock.lock();
            Map<String, List<Catelog2Vo>> dataFromDb ;
            try {
                dataFromDb = getDataFromDb();
            }finally {
              lock.unlock();
            }
            return dataFromDb;

    }
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedis() {
        //1.占分布锁 去redis占坑
        String token = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token,300,TimeUnit.SECONDS);//300秒自动删除
        if (lock){
            System.out.println("获取分布锁成功....");
            //加锁成功 执行业务
            //2.设置过期时间 必须和加锁同步 原子
//            redisTemplate.expire("lock",30,TimeUnit.SECONDS);//30秒自动删除
            Map<String, List<Catelog2Vo>> dataFromDb ;
            try {
                 dataFromDb = getDataFromDb();
            }finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                Long local = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
            }

            //释放锁
//            redisTemplate.delete("lock");
            //获取值对比+对比成功删除 要原子性 同步 lua脚本解锁
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (token.equals(lockValue)){
//                redisTemplate.delete("lock");
//            }

            return dataFromDb;


        }else {
            //加锁失败 重试
            System.out.println("获取分布锁失败....等待重试");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDbWithRedis();//自旋重试

        }





    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogjson = redisTemplate.opsForValue().get("catalogjson");
        if(!StringUtils.isEmpty(catalogjson)){
            //缓存不为空，直接返回
            Map<String, List<Catelog2Vo>> result=JSON.parseObject(catalogjson,new TypeReference< Map<String, List<Catelog2Vo>>>(){});
            return result;
        }
        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查出所有1级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    //每一个的一级分类，查到这个一级分类下的二级分类
                    List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
                    List<Catelog2Vo> catelog2Vos = null;
                    if (categoryEntities != null) {

                        catelog2Vos = categoryEntities.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            //找当前分类的三级分类
                            List<CategoryEntity> level3Vo = getParent_cid(selectList,l2.getCatId());
                            if (level3Vo!=null){
                                List<Catelog2Vo.Catelog3Vo> collect = level3Vo.stream().map(l3 -> {
                                    //封装指定格式
                                    Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                    return catelog3Vo;
                                }).collect(Collectors.toList());
                                catelog2Vo.setCatalog3List(collect);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());


                    }

                    return catelog2Vos;
                }

        ));
        redisTemplate.opsForValue().set("catalogjson", JSON.toJSONString(parent_cid),1, TimeUnit.DAYS);

        return parent_cid;
    }

    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocal() {
        synchronized (this){
            String catalogjson = redisTemplate.opsForValue().get("catalogjson");
            if(!StringUtils.isEmpty(catalogjson)){
                //缓存不为空，直接返回
                Map<String, List<Catelog2Vo>> result=JSON.parseObject(catalogjson,new TypeReference< Map<String, List<Catelog2Vo>>>(){});
                return result;
            }
            //将数据库的多次查询变为一次
            List<CategoryEntity> selectList = baseMapper.selectList(null);
            //查出所有1级分类
            List<CategoryEntity> level1Categorys = getParent_cid(selectList,0L);
            //封装数据
            Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                        //每一个的一级分类，查到这个一级分类下的二级分类
                        List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
                        List<Catelog2Vo> catelog2Vos = null;
                        if (categoryEntities != null) {

                            catelog2Vos = categoryEntities.stream().map(l2 -> {
                                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                //找当前分类的三级分类
                                List<CategoryEntity> level3Vo = getParent_cid(selectList,l2.getCatId());
                                if (level3Vo!=null){
                                    List<Catelog2Vo.Catelog3Vo> collect = level3Vo.stream().map(l3 -> {
                                        //封装指定格式
                                        Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                                        return catelog3Vo;
                                    }).collect(Collectors.toList());
                                    catelog2Vo.setCatalog3List(collect);
                                }
                                return catelog2Vo;
                            }).collect(Collectors.toList());


                        }

                        return catelog2Vos;
                    }

            ));
            redisTemplate.opsForValue().set("catalogjson", JSON.toJSONString(parent_cid),1, TimeUnit.DAYS);

            return parent_cid;
        }

    }

    private List<CategoryEntity> getParent_cid(  List<CategoryEntity> selectList,Long  parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId,  List<Long> paths){
        paths.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid()!=0){
                findParentPath(entity.getParentCid(),paths);
        }
        return paths;
    }


    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
           categoryEntity.getParentCid() == root.getCatId()
        ).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            //2.菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}